import type { InternalAxiosRequestConfig, AxiosResponse} from 'axios'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { objToFormData } from '@/utils'

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    if(config.method === 'post' && config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
        config.data = qs.stringify(config.data)
    } else if(config.method === 'post' && config.headers['Content-Type'] === 'multipart/form-data' && !(config.data instanceof FormData)) {
        config.data = objToFormData(config.data)
    } else if(config.method === 'get' && config.params) {
        let url = config.url as string   
        url += '?'
        for(const key of Object.keys(config.params)) {
            const value = config.params[key]
            if(value !== undefined && value !== null) {
                url += `${key}=${encodeURIComponent(value)}&`
            }
        }
        url = url.substring(0, url.length - 1)
        config.params = {}
        config.url = url
    }

    return config
}

const defaultResponseInterceptors = (response: AxiosResponse) => {
    if(response?.config?.responseType === 'blob') {
        return response
    }

    if(response.status >= 200 && response.status < 300) {
        if("success" in response.data && !response.data.success) {
            ElMessage.error(response?.data?.message);
        }
        return response.data
    }
    // if(response.status === 401) {
    //     ElMessage.error(response?.data?.message)
    //     // todo 退出登录
    //     userStore.logout()
    //     router.push('/login')
    // }
    // if(response.status === 403) {
    //     if(response.data.message) {
    //         ElMessage.error(response?.data?.message)
    //     } else {
    //         ElMessage.error("权限不足")
    //     }
    // }
    // if(response.status === 500) {
    //     ElMessage.error('后台程序发生错误')
    // }
}

export { defaultRequestInterceptors, defaultResponseInterceptors}